package com.wjk.kylin.mall.order.mq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitProducer implements MyProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Async
    @Override
    public void sendTtlMsg(MessageDTO dto, Integer delayTime) {
        String message = JSON.toJSONString(dto);

        log.info("开始发送延时消息-msg:{},delayTime:{}", message, delayTime);

        //TODO
        //死信实现延时队列，只会检查第一个消息是否过期，后面的消息就算比第一个失效时间短，也不会放到死信中。
        //使用rabbitmq 延时插件 实现同一个队列不同的失效时间。

        //设置过期时间
//        MessagePostProcessor messagePostProcessor = e -> {
//            MessageProperties messageProperties = e.getMessageProperties();
////            设置编码
//            messageProperties.setContentEncoding("utf-8");
////            设置过期时间10*1000毫秒(最终过期时间取x-message-ttl和messageProperties.setExpiration的最小值
//            messageProperties.setExpiration(String.valueOf(ttl));
//            return e;
//        };

        //同于RabbitCallback confirm 的数据
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("1");

        //插件实现
        rabbitTemplate.convertAndSend(
                DelayedRabbitConfig.DELAYED_EXCHANGE, DelayedRabbitConfig.DELAYED_ROUTING, message,
                msg -> {
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                }, correlationData);

        log.info("结束发送延时消息-msg:{},delayTime:{}", message, delayTime);
    }

}
